/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年7月23日
 */
package com.massyframework.beanskin.runtime.service.scriptengine;

import java.util.Objects;
import java.util.function.Predicate;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import com.massyframework.beanskin.Module;
import com.massyframework.beanskin.assembly.Assembly;
import com.massyframework.beanskin.fragment.Fragment;
import com.massyframework.beanskin.plugin.Plugin;
import com.massyframework.beanskin.service.ServiceFactory;
import com.massyframework.beanskin.util.classloading.ClassLoaderUtils;
import com.massyframework.beanskin.util.classloading.MixinClassLoader;

/**
 * 脚本引擎服务工厂
 * @author huangkh
 *
 */
public class ScriptEngineServiceFactory implements ServiceFactory<ScriptEngine> {
	
	private final String name;

	/**
	 * 
	 */
	public ScriptEngineServiceFactory(String name) {
		this.name = Objects.requireNonNull(name, "\"name\" cannot be null.");
		
	}

	@Override
	public ScriptEngine getService(Module<?> module) {
		return this.createScriptEngine(module);
	}
	
	/**
	 * 创建脚本引擎
	 * @return {@link ScriptEngine}
	 */
	public ScriptEngine createScriptEngine(Module<?> module) {
		MixinClassLoader classLoader = new MixinClassLoader(
				module.getModuleClassLoader(), this.getClass().getClassLoader());
		ClassLoader contextLoader = ClassLoaderUtils.setThreadContextClassLoader(classLoader);
		
		try {
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine result = manager.getEngineByName(this.name);
			
			
			//graal-js支持 和java适配的指令
			Bindings bindings = result.getBindings(ScriptContext.ENGINE_SCOPE);
			bindings.put("polyglot.js.allowHostAccess", true);
			bindings.put("polyglot.js.allowHostClassLookup", (Predicate<String>) s -> true);
				
			if (module instanceof Assembly) {
				result.put("assembly", module);
			}else {
				if (module instanceof Fragment) {
					result.put("fragment", module);
				}else {
					if (module instanceof Plugin) {
						result.put("plugin", module);
					}else {
						result.put("library", module);
					}
				}
			}
			
			return result;
		}finally {
			Thread.currentThread().setContextClassLoader(contextLoader);
		}
	}
	
	
}
